﻿#include <QVariant>
#include <QSqlField>
#include "JZDbTable.h"

JZDbTable::JZDbTable()
{
    keyIndex = -1;
}

JZDbTable::~JZDbTable()
{
}


QString JZDbTable::generateCreateTableQuery() const
{
    QString query = "CREATE TABLE IF NOT EXISTS " + tableName + " (";
    for (int i = 0; i < record.count(); ++i) {
        QSqlField field = record.field(i);
        query += field.name() + " ";
        switch (field.type()) {
            case QVariant::Int:
            case QVariant::LongLong:
                query += "INTEGER";
                break;
            case QVariant::Double:
                query += "REAL";
                break;
            case QVariant::String:
                query += "TEXT";
                break;
            case QVariant::ByteArray:
                query += "BLOB";
                break;
            case QVariant::DateTime:
                query += "INTEGER";
                break;
            default:
            {
                Q_ASSERT(0); // 处理不支持的字段类型，这里可以抛出异常或者返回错误码，具体取决于你的需求
                break;
            }
        }
        if (i == keyIndex) {
            query += " PRIMARY KEY";
            if (field.isAutoValue()) {
                query += " AUTOINCREMENT";
            }
        }
        if (i < record.count() - 1) {
            query += ", ";
        }
    }
    query += ")";

    return query;
}